package com.liuzh.kaoyanspringboot.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.liuzh.kaoyanspringboot.common.Constants;
import com.liuzh.kaoyanspringboot.entity.User;
import com.liuzh.kaoyanspringboot.exception.ServiceException;
import com.liuzh.kaoyanspringboot.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Component
public class TokenUtils {

    private static UserService staticUserService;
    @Resource
    private UserService userService;

    @PostConstruct
    public void setUserService() {
        staticUserService = userService;
    }
    /**
     * 生成Token
     * @return
     */
    public static String genToken(String userId, String sign) {
        return  JWT.create().withAudience(userId) // 将 userId 保存到 token 里面,作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(),1)) //一小时后token过期
                .sign(Algorithm.HMAC256(sign)); // 以 password 作为 token 的密钥
    }
    /**
     * 获取当前管理员信息
     * @return user
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest  request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); //获取当前请求
            String token = request.getHeader("token");   // 得到token
            String userId = JWT.decode(token).getAudience().get(0);
            if (StrUtil.isNotBlank(token)) {
                return staticUserService.getById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            throw new ServiceException(Constants.CODE_401, "token 为空，nihap");
        }
        return null;
    }
}
